global class OptimizeTriggerScheduler implements schedulable,Database.Batchable<sObject>,Database.Stateful
{
    global OptimizeTriggerScheduler(){}
    
    global Database.QueryLocator start(Database.BatchableContext BC){
        String sql='Select Id,RoutingPlanAndVisit__r.OwnerId,OutletName_del__c,Start_Time__c ,'+
                    'SSYActivityAchievement__c,StartDate__c, OwnerId__c, HasRun_SSYToDashboard__c'+
                    ' From In_Store_Visit__c Where HasRun_SSYToDashboard__c =false '+
                    'and SSYACTIVITYACHIEVEMENT__C=true';
       return Database.getQueryLocator(sql);
    }
    
    global void execute(Database.BatchableContext BC, List<sObject> scope){
        Map<String,TradeDashboardDetails__c> DashUpsertMapList=new Map<String,TradeDashboardDetails__c>();
        Map<String,SSYActivityExecutionTracking__c> SSYUpsertMapList=new Map<String,SSYActivityExecutionTracking__c>();
        List<In_Store_Visit__c> AllInStoreVisitList=new List<In_Store_Visit__c>();
        DateTime dt;
        Date d;
        String keyString,KeySSYString; 
        In_Store_Visit__c st;  
        
        for(SObject obj:scope)
        {
            st=(In_Store_Visit__c)obj;
            st.HasRun_SSYToDashboard__c=true;
            dt=st.Start_Time__c;
            d=Date.newInstance(dt.year(),dt.month(),1);
            //TradeDashboardDetails__c处理逻辑
            keyString=String.valueOf(st.OutletName_del__c)+String.valueOf(st.RoutingPlanAndVisit__r.OwnerId)+String.valueOf(d)+'SSY Activity Achievement';
            TradeDashboardDetails__c sae=new TradeDashboardDetails__c();
            sae.CriticalEnabler__c='SSY Activity Achievement';
            sae.Outlet__c=st.OutletName_del__c;
            //ScoreStandard__c.getValues('SSY Activity Achievement').Standard__c
            sae.ScoreStandard__c=ScoreStandard__c.getValues('SSY Activity Achievement').Standard__c;
            sae.Actual__c=1;
            sae.OwnerId=st.RoutingPlanAndVisit__r.OwnerId;
            sae.SalesMonth__c=d;
            sae.PrimaryKeyId__c=KeyString;
            sae.TSR__c=st.RoutingPlanAndVisit__r.OwnerId;
            DashUpsertMapList.put(KeyString,sae);
            
            //SSYActivityExecutionTracking__c逻辑
            KeySSYString=String.valueOf(st.OutletName_del__c)+String.valueOf(st.RoutingPlanAndVisit__r.OwnerId)+String.valueOf(d)+'SSYActivity';
            SSYActivityExecutionTracking__c ssy=new SSYActivityExecutionTracking__c();
            ssy.OutletName__c=st.OutletName_del__c;
            ssy.ExecutedSSY__c=1;
            ssy.SalesMonth__c=d;
            ssy.OwnerId=st.RoutingPlanAndVisit__r.OwnerId;
            ssy.PrimaryKeyId__c=KeySSYString;
            SSYUpsertMapList.put(KeySSYString,ssy);
        }
        
        if(DashUpsertMapList.size()>0)
            upsert DashUpsertMapList.values() PrimaryKeyId__c;
        if(SSYUpsertMapList.size()>0)
            upsert SSYUpsertMapList.values() PrimaryKeyId__c; 
            
         if(AllInStoreVisitList.size()>0)
            update AllInStoreVisitList;  
    }
    global void finish(Database.BatchableContext BC){
         
    }
    
   /* public void  WriteInStoreVisitBySSYToDashboard() //in store visit  using HasRun_SSYToDashboard__c 
    {
        List<TradeDashboardDetails__c> ssyList=new List<TradeDashboardDetails__c>();
        Map<String,TradeDashboardDetails__c> DashUpsertMapList=new Map<String,TradeDashboardDetails__c>();
        Map<String,SSYActivityExecutionTracking__c> SSYUpsertMapList=new Map<String,SSYActivityExecutionTracking__c>();
        Date DToday=Date.newInstance(Date.today().year(),Date.today().month(),1);
        DateTime dt;
        Date d;
        String keyString,KeySSYString;   
        
        List<In_Store_Visit__c> AllInStoreVisitList = [Select Id,RoutingPlanAndVisit__r.OwnerId,OutletName_del__c,Start_Time__c ,
                                               SSYActivityAchievement__c,StartDate__c, OwnerId__c, HasRun_SSYToDashboard__c 
                                               From In_Store_Visit__c Where HasRun_SSYToDashboard__c =: false 
                                               and SSYACTIVITYACHIEVEMENT__C=: true limit 5000];
          
        for(In_Store_Visit__c st:AllInStoreVisitList)
        {
            st.HasRun_SSYToDashboard__c=true;
            dt=st.Start_Time__c;
            d=Date.newInstance(dt.year(),dt.month(),1);
            //TradeDashboardDetails__c处理逻辑
            keyString=String.valueOf(st.OutletName_del__c)+String.valueOf(st.RoutingPlanAndVisit__r.OwnerId)+String.valueOf(d)+'SSY Activity Achievement';
            TradeDashboardDetails__c sae=new TradeDashboardDetails__c();
            sae.CriticalEnabler__c='SSY Activity Achievement';
            sae.Outlet__c=st.OutletName_del__c;
            //ScoreStandard__c.getValues('SSY Activity Achievement').Standard__c
            sae.ScoreStandard__c=ScoreStandard__c.getValues('SSY Activity Achievement').Standard__c;
            sae.Actual__c=1;
            sae.OwnerId=st.RoutingPlanAndVisit__r.OwnerId;
            sae.SalesMonth__c=d;
            sae.PrimaryKeyId__c=KeyString;
            sae.TSR__c=st.RoutingPlanAndVisit__r.OwnerId;
            DashUpsertMapList.put(KeyString,sae);
            
            //SSYActivityExecutionTracking__c逻辑
            KeySSYString=String.valueOf(st.OutletName_del__c)+String.valueOf(st.RoutingPlanAndVisit__r.OwnerId)+String.valueOf(d)+'SSYActivity';
            SSYActivityExecutionTracking__c ssy=new SSYActivityExecutionTracking__c();
            ssy.OutletName__c=st.OutletName_del__c;
            ssy.ExecutedSSY__c=1;
            ssy.SalesMonth__c=d;
            ssy.OwnerId=st.RoutingPlanAndVisit__r.OwnerId;
            ssy.PrimaryKeyId__c=KeySSYString;
            SSYUpsertMapList.put(KeySSYString,ssy);
        }
        if(DashUpsertMapList.size()>0)
            upsert DashUpsertMapList.values() PrimaryKeyId__c;
        if(SSYUpsertMapList.size()>0)
            upsert SSYUpsertMapList.values() PrimaryKeyId__c; 
            
         if(AllInStoreVisitList.size()>0)
            update AllInStoreVisitList;  
    }
    */
    public void AddOrderItemRecordToOutletOfftake()
    {  
        List<OutletMonthlyOfftake__c> omoList=new List<OutletMonthlyOfftake__c>();
        List<Order_Item__c> UorderList = new List<Order_Item__c>();
        
        List<Order_Item__c> orderList = [Select Id,Order_Name__c, OrderNumber__c, HasRun_OutletOfftake__c,VisitDate__c, Price_pre_tax__c, 
                                         Product_Name__c,Price_after_tax__c,OwnerId__c, RealPackage__c,OutletName__c 
                                         From Order_Item__c Where HasRun_OutletOfftake__c =: false limit 4000];
    
        for(Order_Item__c oi:orderList )
        {
            DateTime dt=oi.VisitDate__c;
            Date d=Date.newInstance(dt.year(), dt.month(), 1);
            OutletMonthlyOfftake__c omo=new OutletMonthlyOfftake__c();
            omo.OutletName__c=oi.OutletName__c;
            omo.ProductName__c=oi.Product_Name__c;
            omo.SalesVolume__c=oi.OrderNumber__c;
            omo.SalesValue__c=oi.OrderNumber__c*oi.Price_pre_tax__c;
            omo.MonthlyOfftakeDate__c=d;
            omo.OwnerId=oi.OwnerId__c;
            omoList.add(omo);
            oi.HasRun_OutletOfftake__c = true;
            UorderList.add(oi);
        }
        
        insert omoList;  
        update UorderList;
    }

    global void execute(schedulablecontext sc)
    {
        AddOrderItemRecordToOutletOfftake();
        Database.executeBatch(new OptimizeTriggerScheduler());
      //  WriteInStoreVisitBySSYToDashboard();
        
    }
}